package com.itheima.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理
 * @ControllerAdvice 默认拦截所有controller发出的异常
 * @ResrControllerAdvice  默认拦截所有 RestController 发出的异常, 且自带 @ResponseBody
 *      @ResponseBody  将方法返回的数据转化为json字符串给到响应体输出
 */
/*
@ResponseBody
@ControllerAdvice(annotations = {RestController.class, Controller.class})
*/
@Slf4j
@RestControllerAdvice(annotations = {RestController.class, Controller.class})
public class GlobalExceptionHandler {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException e){
        log.info(e.getMessage());
        if (e.getMessage().contains("Duplicate entry")) {
            String[] s = e.getMessage().split(" ");
            String name = s[2];
            return R.error("用户" + name + "已存在");
        }
        return R.error("未知错误");
    }

    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException e){
        log.info(e.getMessage());
        return R.error(e.getMessage());
    }

}
